<template>
  <div id="Catalog" class="catalog-container">
    <div id="Cart" class="cart-wrapper">
      <h2 class="cart-title">Shopping Cart</h2>
      <form @submit.prevent="updateCart" class="cart-form">
        <table class="cart-table">
          <thead>
          <tr>
            <th>商品项 ID</th>
            <th>具体产品ID</th>
            <th>单价</th>
            <th>数量</th>
            <th>总价</th>
            <th></th>
          </tr>
          </thead>
          <tbody>
          <!-- 购物车为空的情况 -->
          <tr v-if="cartStore.cartItems.length === 0">
            <td colspan="6" class="empty-cart-message">
              <b>购物车为空</b>
            </td>
          </tr>
          <!-- 展示购物车商品 -->
          <tr v-else v-for="item in cartStore.cartItems" :key="item.itemid" class="cart-item">
            <td>
              <router-link
                  :to="{ name: 'ItemDetail', params: { itemId: item.itemId } }"
                  class="detail-button"
              >
                {{ item.itemId }}
              </router-link>
            </td>
            <td>{{ item.productId }}</td>
            <td class="price">$ {{ formatPrice(item.listPrice) }}</td>
            <td>
              <input
                  type="number"
                  min="1"
                  v-model="item.quantity"
                  @change="updateCartItem(item)"
                  class="item-quantity-input"
              />
            </td>
            <td class="price">$ {{ formatPrice(item.total) }}</td>
            <td>
              <button @click.prevent="removeItem(item.cartItemId)" class="remove-button">
                删除
              </button>
            </td>
          </tr>
          </tbody>
          <tfoot>
          <tr>
            <td colspan="6" class="subtotal-section">
              <!-- 修改为使用 cartStore 的 totalPrice -->
             Sub Total: <span class="subtotal-price">$ {{ formatPrice(cartStore.totalPrice) }}</span>
              <input type="submit" value="更新购物车" class="update-button" />
            </td>
          </tr>
          </tfoot>
        </table>
      </form>
      <!-- 购物车有商品时显示结算按钮 -->
      <router-link
          v-if="cartStore.cartItems.length > 0"
          :to="{ name: 'order',query: { cartItems: JSON.stringify(cartStore.cartItems) }}"
          class="checkout-button"
      >
        结算
      </router-link>
    </div>
    <!-- 这里暂时模拟 MyList 部分，你可以根据实际情况完善 -->

    <div id="Separator" class="separator"></div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/userStore';
import { useCartStore } from '@/stores/cartStore';
// 导入 cartService
import {
  fetchCartItems,
  addCartItem,
  updateCartItem as updateCartItemApi,
  removeCartItem as removeCartItemApi
} from '@/api/cartService';

const userStore = useUserStore();
const cartStore = useCartStore();

const userId = computed(() => userStore.user.userid);

// 格式化价格
const formatPrice = (price) => {
  return parseFloat(price).toFixed(2);
};

// 页面加载时获取用户购物车项
const loadCartItems = async () => {
  console.log('当前用户 ID:', userId.value); // 打印当前用户 ID
  try {
    await cartStore.fetchCart(userId.value);
    console.log('获取到的购物车数据:', cartStore.cartItems);
  } catch (error) {
    console.error('获取购物车数据失败:', error);
  }
};

onMounted(async () => {
  await loadCartItems();
  setTimeout(() => {
    console.log('延迟后购物车数据:', cartStore.cartItems);
  }, 2000); // 延迟 2 秒
});

const router = useRouter();

// 更新购物车项
const updateCartItem = async (item) => {
  try {
    item.total = (item.listPrice * item.quantity).toFixed(2);
    await updateCartItemApi(item);
    console.log('更新成功');
  } catch (error) {
    console.error('更新购物车项失败:', error);
  }
};

// 移除商品方法
const removeItem = async (cartItemId) => {
  try {
    await removeCartItemApi(cartItemId);
    await cartStore.fetchCart(userId.value); // 重新获取购物车数据
    console.log('删除成功');
  } catch (error) {
    console.error('移除商品失败:', error);
  }
};

// 更新购物车方法
const updateCart = async () => {
  console.log('更新购物车...');
  for (const item of cartStore.cartItems) {
    await updateCartItem(item);
  }
};

// 模拟登录账户数据
const loginAccount = ref({
  listOption: true
});

onMounted(fetchCartItems);

</script>

<style scoped>
.catalog-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.cart-wrapper {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.cart-title {
  text-align: center;
  color: #333;
  margin-bottom: 20px;
  font-size: 24px;
}

.cart-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.cart-table th,
.cart-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.cart-table th {
  background-color: #f5f5f5;
  font-weight: 600;
}

.empty-cart-message {
  text-align: center;
  color: #666;
  padding: 20px 0;
}

.item-link {
  color: #007bff;
  text-decoration: none;
  transition: color 0.3s ease;
}

.item-link:hover {
  color: #0056b3;
}

.item-description {
  max-width: 200px;
  word-wrap: break-word;
}

.item-quantity-input {
  width: 60px;
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.price {
  font-weight: 600;
  color: #28a745;
}

.remove-button {
  padding: 6px 12px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.remove-button:hover {
  background-color: #c82333;
}

.subtotal-section {
  font-weight: 600;
  font-size: 18px;
}

.subtotal-price {
  color: #28a745;
  margin-left: 10px;
}

.update-button {
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 20px;
  transition: background-color 0.3s ease;
}

.update-button:hover {
  background-color: #0056b3;
}

.checkout-button {
  display: inline-block;
  padding: 10px 20px;
  background-color: #28a745;
  color: white;
  text-decoration: none;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.checkout-button:hover {
  background-color: #218838;
}

.my-list {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.separator {
  height: 20px;
}
</style>
